package com.jy.appmarket.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;

import android.util.Log;

public class CommandExecutor {
	private static final String TAG = "CommandExecutor";
	
	public static int execute(String cmd, String[][] outputs) {
		return execute(cmd, true, outputs);
	}

	public static int execute(String cmd, boolean waitReaders, String[][] outputs) {
		int status = -1;
		ArrayList<String> errorOutput = new ArrayList<String>();
		ArrayList<String> stdOutput = new ArrayList<String>();
		try {
			Process proc = Runtime.getRuntime().exec(cmd);
			status = grabProcessOutput(proc, errorOutput, stdOutput, waitReaders);
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		if(outputs != null && outputs.length >= 2){
			String[] errs = errorOutput.toArray(new String[errorOutput.size()]);
			outputs[0] = errs;
			
			String[] stds = stdOutput.toArray(new String[stdOutput.size()]);
			outputs[1] = stds;
		}
		
		return status;
	}

	private static int grabProcessOutput(final Process process, final ArrayList<String> errorOutput,
			final ArrayList<String> stdOutput, boolean waitForReaders) throws InterruptedException {

		assert errorOutput != null;
		assert stdOutput != null;
		Thread t1 = new Thread("t1") {
			@Override
			public void run() {
				InputStreamReader is = new InputStreamReader(process.getErrorStream());
				BufferedReader errReader = new BufferedReader(is);

				try {
					while (true) {
						String line = errReader.readLine();
						if (line != null) {
							Log.e(TAG, "error:" + line);
							errorOutput.add(line);
						} else {
							break;
						}
					}
				} catch (IOException e) {
					e.printStackTrace();
					// do nothing.
				}
			}
		};

		Thread t2 = new Thread("t2") {
			@Override
			public void run() {
				InputStreamReader is = new InputStreamReader(process.getInputStream());
				BufferedReader outReader = new BufferedReader(is);

				try {
					while (true) {
						String line = outReader.readLine();
						if (line != null) {
							Log.d(TAG, line);
							stdOutput.add(line);
						} else {
							break;
						}
					}
				} catch (IOException e) {
					e.printStackTrace();
					// do nothing.
				}
			}
		};
		
		t1.start();
		t2.start();

		if (waitForReaders) {
			try {
				t1.join();
				t2.join();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		return process.waitFor();
	}

}
